package com.imooc.authorization.context;

import com.imooc.authorization.dto.Accordion;
import com.imooc.authorization.entity.User;

import javax.servlet.*;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import javax.servlet.Filter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.LogicalHandler;

/**
 * Created by Administrator on 2016/8/28.
 */
//TODO 待完成
public class UserContextFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        ResponseContext.setCurrent(response);

        if(request.getRequestURI().contains("login")){
            Cookie cookie=new Cookie("auth",null);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            chain.doFilter(servletRequest,servletResponse);
            return;
        }
        if(request.getRequestURI().contains("index.jsp")){

            chain.doFilter(servletRequest,servletResponse);
            return;
        }

        if(request.getRequestURI().endsWith(".css")||request.getRequestURI().endsWith(".js")
                ||request.getRequestURI().endsWith(".jpg")||request.getRequestURI().endsWith(".gif")||request.getRequestURI().contains("easyui")){

            chain.doFilter(servletRequest,servletResponse);
            return;
        }
        String cookieValue="";
        if (null!=request.getCookies()){

            for (Cookie cookie:request.getCookies()){
                if (Objects.equals(cookie.getName(),"auth")){
                    cookieValue=cookie.getValue();
                    break;
                }

            }
        }

        byte[] bytes= Base64.getDecoder().decode(cookieValue);

        String auth=new String(bytes);

        String[] array=auth.split("\\$");
        if(2==array.length){
            //从缓存中取用户
            User user = LoginUserCache.get(array[0]);//如果服务器重启，cache将消失，为Null
            if(null==user){
                        //服务器重启，加载客户端cookie
                LoginUserHelper helper=WebApplicationContext.getBean(LoginUserHelper.class);
                helper.executeLogin(array[0],array[1]);
                user=LoginUserCache.get(array[0]);

            }
            if(null!=user && Objects.equals(user.getPassword(),array[1])){

                List<Accordion> accordions=LoginUserCache.getAccordions(user.getName());
                request.setAttribute("accordions",accordions);
                UserContext.setCurrent(user);
                //更新cookie
                LoginUserCache.setCookie(user);
                chain.doFilter(servletRequest,servletResponse);
                return;

            }else{
                Cookie cookie=new Cookie("auth",null);
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                response.sendRedirect("/index.jsp");
            }
        }else{
            Cookie cookie=new Cookie("auth",null);
            cookie.setMaxAge(0);
            response.addCookie(cookie);

        }

        chain.doFilter(servletRequest,servletResponse);


    }

    @Override
    public void destroy() {

    }
}
